<template>
  <div class="container_order">
    <van-nav-bar title="确认承运" fixed @click-left="onClickLeft">
      <van-icon name="arrow-left" slot="left" color="#333" size="0.6rem" />
    </van-nav-bar>
    <van-cell-group class="count cod" @click="deliver" v-if="deliverVal">
      <div class="cod_box">
        <p>{{faAddress}}</p>
        <div>
          <van-tag color="#f2826a" v-if="deliverValArr.filter(item=>item == '需要提货').length" plain>提</van-tag>
          <van-tag
            color="#f2826a"
            v-if="deliverValArr.filter(item=>item == '需要装车').length"
            style="marginLeft: 5px"
            plain
          >装</van-tag>
          <van-tag
            color="#f2826a"
            v-if="deliverValArr.filter(item=>item == '需要过磅').length"
            style="marginLeft: 5px"
            plain
          >过磅</van-tag>
        </div>
      </div>
      <van-cell center :title="facount" />
    </van-cell-group>
    <van-cell-group v-else class="count_fist" @click="deliver">
      <van-cell center title="发货信息" />
      <van-cell center title="点击填写发货人地址信息" is-link />
    </van-cell-group>

    <van-cell-group class="count cod" @click="receiving" v-if="receivingVal">
      <div class="cod_box">
        <p>{{shouAddress}}</p>
        <div>
          <van-tag
            color="#f2826a"
            v-if="receivingValArr.filter(item=>item == '需要送货').length"
            plain
          >送</van-tag>
          <van-tag
            color="#f2826a"
            v-if="receivingValArr.filter(item=>item == '需要卸车').length"
            style="marginLeft: 5px"
            plain
          >卸</van-tag>
        </div>
      </div>
      <van-cell center :title="shoucount" />
    </van-cell-group>

    <van-cell-group class="count" @click="receiving" v-else>
      <van-cell center title="收货地址" />
      <van-cell center title="点击填写收货人地址信息" is-link />
    </van-cell-group>

    <van-cell-group class="count" @click="onOver">
      <van-cell title="货物清单" is-link />
      <van-cell title="总件数" :value="number" />
      <van-cell title="总重量(公斤)" :value="KG" />
      <van-cell title="总体积(方)" :value="M3" />
    </van-cell-group>
    <van-cell-group class="count" @click="feedetails">
      <van-cell title="费用详情" is-link />
      <van-cell title="上游应收合计" :value="UpMoney" />
      <van-cell title="下游应付合计" :value="DownMoney" />
    </van-cell-group>
    <van-cell-group class="count">
      <van-cell title="其他" />
      <van-cell title="付款方式" :value="paymentMony" is-link @click="payment" />
      <van-cell title="选择优惠券" :value="paymentLiner" is-link @click="showTypeLiner" />
      <van-field v-model="delivery" label="货物保价" placeholder="请输入" input-align="right" />
      <van-cell title="短信服务设置" :value="ShortMessage" is-link @click="sms" />
      <van-cell
        title="查货人"
        @click="() => $router.push({path:'/check', query:query})"
        :value="check"
        is-link
      />
      <van-field v-model="maks" label="备注" placeholder="请输入" input-align="right" />
    </van-cell-group>
    <div style="height: 57px"></div>
    <div class="buton">
      <van-button class="butonO" type="primary" size="large">取消</van-button>
      <van-button class="butonT" type="primary" @click="onOK" size="large">确定</van-button>
    </div>
    <van-action-sheet v-model="show" title="付款方式">
      <div class="content">
        <div class="box_added">
          <div class="checkSteper">
            <ul>
              <li
                :class="checkArr.filter(item => item == '现付').length ? 'active' : ''"
                @click="onclick('现付')"
              >现付</li>
              <li
                :class="checkArr.filter(item => item == '月结').length? 'active' : ''"
                @click="onclick('月结')"
              >月结</li>
            </ul>
          </div>
        </div>
      </div>
    </van-action-sheet>
    <van-action-sheet
      v-model="showType"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
      @select="onSelect"
    />
    <!-- </van-popup> -->
  </div>
</template>

<script>
import Vue from "vue";
import { Tag, Toast } from "vant";
import { selLottery, addOrder, confirmSaveModifyOrder } from "@/api/add";
import { orderSelect, orderChange } from "@/api/order";
Vue.use(Tag);
Vue.use(Toast);
export default {
  data() {
    return {
      delivery: "",
      show: false,
      checkArr: ["现付"],
      paymentMony: "现付",
      paymentLiner: "暂不使用优惠卷",
      showType: false,
      maks: "",
      actions: [{ name: "暂不使用优惠券" }],
      query: {},
      shouAddress: "",
      faAddress: "",
      number: "请输入",
      shoucount: "",
      facount: "",
      KG: "请输入",
      M3: "请输入",
      check: "请输入",
      UpMoney: "请输入",
      DownMoney: "请输入",
      ShortMessage: "请配置",
      kauserid: "",
      receivingVal: null,
      deliverVal: null,
      receivingValArr: [],
      deliverValArr: [],
      linerARr: [],
      orderId: "",
      res:{}
    };
  },
  created() {
    let orderid = this.$router.history.current.query.orderId;
    orderSelect(orderid).then((res) => {
      console.log(res);
      this.res = res
      this.kauserid = res.data.kaUserId;
      this.orderId = orderid;
      if (!sessionStorage.getItem("deliver")) {
        let deliver = {
          KaUabLinker: res.data.shrpPeopleName,
          KaUabTel: res.data.shrpPeopleTel,
          KaUabType: 1,
          KaUserId: res.data.kaUserId,
          KaUabDes: res.data.shrpDes,
          PROVINCENAME: res.data.shrpProvinceName,
          CITYNAME: res.data.shrpCityName,
          AREANAME: res.data.shrpAreaName,
          KaUabArea: res.data.shrpAreaCode,
          KaUabCity: res.data.shrpCityCode,
          KaUabProvince: res.data.shrpProvinceCode,
          KaUabStatus: 1,
          KaAppointmentStart: res.data.kaAppointmentStart,
          KaAppointmentEnd: res.data.kaAppointmentEnd,
          shrpLatitude: res.data.shrpLatitude ? res.data.shrpLatitude : null, // 发货经度
          shrpLongitude: res.data.shrpLongitude ? res.data.shrpLongitude : null, // 发货纬度
          shortDeptId: res.data.shortDeptId,
          shortDeptName: res.data.shortDeptName,
          shortStationId: res.data.shortStationId,
          shortStationName: res.data.shortStationName,
        };
        let kaPickupArr = [];
        console.log(res.data.kaPickup, res.data.overPump);
        if (res.data.kaPickup == 1) {
          kaPickupArr.push("需要提货");
        }
        if (res.data.overPump == 1) {
          kaPickupArr.push("需要过磅");
        }
        if (res.data.isLoading == 1) {
          kaPickupArr.push("需要装车");
        }
        sessionStorage.setItem("deliver", JSON.stringify(deliver));
        sessionStorage.setItem("deliver_checkArr", JSON.stringify(kaPickupArr));
      }

      if (
        res.data.cneePeopleName != "" &&
        res.data.cneeAreaCode != null &&
        res.data.cneeCityCode != null &&
        res.data.cneeProvinceCode != null &&
        !sessionStorage.getItem("receiving")
      ) {
        let receiving = {
          KaUabLinker: res.data.cneePeopleName,
          KaUabTel: res.data.cneePeopleTel,
          KaUabType: 2,
          KaUserId: res.data.kaUserId,
          KaUabDes: res.data.cneeDes,
          PROVINCENAME: res.data.cneeProvinceName,
          CITYNAME: res.data.cneeCityName,
          AREANAME: res.data.cneeAreaName,
          KaUabArea: res.data.cneeAreaCode,
          KaUabCity: res.data.cneeCityCode,
          KaUabProvince: res.data.cneeProvinceCode,
          KaUabStatus: 1,
          cneeLatitude: res.data.cneeLatitude ? res.data.cneeLatitude : null, // 收货经度
          cneeLongitude: res.data.cneeLongitude ? res.data.cneeLongitude : null, // 收货纬度
        };
        sessionStorage.setItem("receiving", JSON.stringify(receiving));
      }

      if (!sessionStorage.getItem("receiving_checkArr")) {
        let kaPickupArr = [];
        if (res.data.isUnLoading == 1) {
          kaPickupArr.push("需要卸车");
        }
        if (res.data.KaDelivery == 1) {
          kaPickupArr.push("需要送货");
        }
        sessionStorage.setItem(
          "receiving_checkArr",
          JSON.stringify(kaPickupArr)
        );
      }

      if (!sessionStorage.getItem("orderInfo")) {
        let orderinfo = [];
        res.data.kaOrderList.map((item) => {
          orderinfo.push({
            KaGoodName: item.goodsName,
            KaWeightKg: item.kaWeightKg,
            KaVolume: item.kaVolume,
            KaQuantity: item.kaQuantity,
            checkArr: [],
            goodSituation: item.goodSituation,
            kaRemarks: item.insideRemark,
            Fragile: item.fragile,
            Pressurable: item.Pressurable,
            KaGoodPicture: item.picturesUrl,
          });
        });
        sessionStorage.setItem("orderInfo", JSON.stringify(orderinfo));
      }

      if (!JSON.parse(sessionStorage.getItem("feed"))) {
        if (res.data.isManual) {
          let feed = {
            KaDelivery: res.data.kaDelivery,
            PushPlatform: res.data.PushPlatform,
            PushPlatformPc: res.data.pushPlatformPc,
            TabArr: ["人工报价"],
            carrierNumber: res.data.carrierNumber,
            carrierPickUp: res.data.carrierPickUp,
            carrierPrice: res.data.carrierPrice,
            carrierSend: res.data.carrierSend,
            kaArSend: res.data.kaArSend,
            kaArFreight: res.data.kaArFreight,
            isManual: res.data.isManual,
            kaCarrierCompanyName: res.data.kaCarrierCompanyName,
            kaCarrierContactMobile: res.data.kaCarrierContactMobile,
            kaCarrierContactName: res.data.kaCarrierContactName,
            kaCarrierId: res.data.kaCarrierId,
            kaIspickUp: res.data.kaIspickUp,
            kaIssend: res.data.kaIssend,
            kaPickup: res.data.kaPickup,
            priceTime: res.data.priceTime,
            kaArPickUp: res.data.kaArPickUp,
            pushPlatform: res.data.pushPlatform
          };
          sessionStorage.setItem("feed", JSON.stringify(feed));
        } else {
          let feedJP = {
            isManual: res.data.isManual, // 0-系统估价  1-人工估价
            KaPickup: res.data.KaPickup, // 人工上游是否提货
            KaDelivery: res.data.KaDelivery, // 人工上游是否送货
            TabArr: ["精拼报价"],
            JPSmoney: res.data.kaTotalPrice,
            JPXmoney: res.data.downCarrierPrice,
          };
          sessionStorage.setItem("feed", JSON.stringify(feedJP));
        }
      }

      this.ondatalist();
    });
  },
  mounted() {
    // selLottery(this.query.kauserId).then(res => {
    //   console.log(res);
    //   this.linerARr = res.data;
    //   this.linerARr.map(item => {
    //     this.actions.push({
    //       name: item.Coudescribe,
    //       LotteryID: item.LotteryID
    //     });
    //   });
    // });
  },

  methods: {
    onCancel() {
      this.showType = false;
    },
    onClickLeft() {
      this.$router.back();
    },
    onshipper() {
      this.$router.push({
        path: "/shipperinfo",
        query: this.query,
      });
    },
    ondatalist() {
      // 获取路径带的用户ID
      this.query = this.$router.history.current.query;
      this.receivingVal = JSON.parse(sessionStorage.getItem("receiving"))
        ? JSON.parse(sessionStorage.getItem("receiving"))
        : null;
      if (this.receivingVal != null) {
        this.shoucount = `${this.receivingVal.CITYNAME} ${this.receivingVal.AREANAME} ${this.receivingVal.KaUabDes} `;
      }
      this.deliverVal = JSON.parse(sessionStorage.getItem("deliver"))
        ? JSON.parse(sessionStorage.getItem("deliver"))
        : null;
      if (this.deliverVal != null) {
        this.facount = `${this.deliverVal.CITYNAME} ${this.deliverVal.AREANAME} ${this.deliverVal.KaUabDes} `;
      }
      this.shouAddress = JSON.parse(sessionStorage.getItem("receiving"))
        ? `${JSON.parse(sessionStorage.getItem("receiving")).KaUabLinker}  ${
            JSON.parse(sessionStorage.getItem("receiving")).KaUabTel
          }`
        : "收货地址";
      this.faAddress = JSON.parse(sessionStorage.getItem("deliver"))
        ? `${JSON.parse(sessionStorage.getItem("deliver")).KaUabLinker} ${
            JSON.parse(sessionStorage.getItem("deliver")).KaUabTel
          }`
        : "发货地址";
      if (JSON.parse(sessionStorage.getItem("orderInfo"))) {
        let num = 0;
        let kgs = 0;
        let m3s = 0;
        if (JSON.parse(sessionStorage.getItem("orderInfo"))) {
          JSON.parse(sessionStorage.getItem("orderInfo")).map((item) => {
            num += Number(item.KaQuantity);
            kgs += Number(item.KaWeightKg);
            m3s += Number(item.KaVolume);
          });
          this.number = num;
          this.KG = kgs;
          this.M3 = m3s;
        }
      }

      if (JSON.parse(sessionStorage.getItem("feed"))) {
        let feed = JSON.parse(sessionStorage.getItem("feed"));
        this.UpMoney = 0;
        this.DownMoney = 0;
        if (feed.TabArr[0] == "人工报价") {
          this.UpMoney += Number(feed.kaArPickUp);
          this.UpMoney += Number(feed.kaArSend);
          this.UpMoney += Number(feed.kaArFreight);
          this.DownMoney += Number(feed.carrierPrice);
          this.DownMoney += Number(feed.carrierPickUp);
          this.DownMoney += Number(feed.carrierSend);
        } else {
          this.UpMoney = feed.JPSmoney;
          this.DownMoney = feed.JPXmoney;
        }
      }

      if (JSON.parse(sessionStorage.getItem("deliver_checkArr"))) {
        this.deliverValArr = JSON.parse(
          sessionStorage.getItem("deliver_checkArr")
        );
      }

      if (JSON.parse(sessionStorage.getItem("receiving_checkArr"))) {
        this.receivingValArr = JSON.parse(
          sessionStorage.getItem("receiving_checkArr")
        );
      }

      if (JSON.parse(sessionStorage.getItem("message"))) {
        let message = JSON.parse(sessionStorage.getItem("message"));
        if (message.medalTit.length != 4) {
          this.ShortMessage = `${message.medalTit.substring(0, 8)}...`;
        } else {
          this.ShortMessage = "均不通知";
        }
      }

      if (JSON.parse(sessionStorage.getItem("check"))) {
        let check = JSON.parse(sessionStorage.getItem("check"));
        this.check = `${check.stockingGoodsMan} - ${check.stockingGoodsMobile}`;
      }
    },
    onclick(val) {
      this.checkArr = [];
      this.checkArr.push(val);
      this.paymentMony = this.checkArr[0];
      this.show = false;
    },
    sms() {
      this.$router.push({
        path: "/sms",
        query: { kauserId: this.kauserid, state: 1, orderId: this.orderId },
      });
    },
    onSelect(val) {
      console.log(val);
      this.paymentLiner = val.name;
    },
    onOver() {
      this.$router.push({
        path: "/goods",
        query: { kauserId: this.kauserid, state: 1, orderId: this.orderId },
      });
    },
    feedetails() {
      if (
        !JSON.parse(sessionStorage.getItem("deliver")) ||
        !JSON.parse(sessionStorage.getItem("receiving"))
      ) {
        Toast.fail("请将发货地址或收货地址信息补全在进行填写");
      } else {
        this.$router.push({
          path: "/feedetails",
          query: { kauserId: this.kauserid, state: 1, orderId: this.orderId },
        });
      }
    },
    receiving() {
      this.$router.push({
        path: "/receiving",
        query: { kauserId: this.kauserid, state: 1, orderId: this.orderId },
      });
    },
    deliver() {
      this.$router.push({
        path: "/deliver",
        query: { kauserId: this.kauserid, state: 1, orderId: this.orderId },
      });
    },
    payment() {
      this.show = !this.show;
    },
    showTypeLiner() {
      this.showType = true;
    },
    onOK() {
      if (!JSON.parse(sessionStorage.getItem("deliver"))) {
        Toast.fail("发货信息不能为空");
        return false;
      }
      if (!JSON.parse(sessionStorage.getItem("orderInfo"))) {
        Toast.fail("货物信息不能为空");
        return false;
      }
      let receiving = JSON.parse(sessionStorage.getItem("receiving"));
      let deliver = JSON.parse(sessionStorage.getItem("deliver"));
      let kauserinfo = JSON.parse(sessionStorage.getItem("kauserinfo"));
      let payment = 0;
      if (this.paymentMony == "现结") {
        payment = 0;
      } else if (this.paymentMony == "月结") {
        payment = 1;
      }
      let list = {
        KaOrderId: this.$router.history.current.query.orderId,
        PushPlatform: 0, // 推送平台
        ShrpPeopleName: deliver.KaUabLinker, // 发货人姓名
        ShrpPeopleTel: deliver.KaUabTel, // 发货人电话
        shrpProvinceCode: deliver.KaUabProvince, //发货省code
        shrpCityCode: deliver.KaUabCity, // 发货市code
        shrpAreaCode: deliver.KaUabArea, // 发货区code
        ShrpDes: `${deliver.KaUabDes}`, // 发货地详细地址
        shortDeptId: deliver.shortDeptId || "", // 营业网点id
        shortStationId: deliver.shortStationId || "", // 站点id
        shortDeptName: deliver.shortDeptName || "", // 营业网点名称
        shortStationName: deliver.shortStationName || "", // 站点名称
        shrpLatitude: deliver.shrpLatitude ? deliver.shrpLatitude : "", // 发货经度
        shrpLongitude: deliver.shrpLongitude ? deliver.shrpLongitude : "", // 发货纬度
        cneeLatitude: receiving ? receiving.cneeLatitude : "", // 收货经度
        cneeLongitude: receiving ? receiving.cneeLongitude : "", // 收货纬度
        CneePeopleName: receiving ? receiving.KaUabLinker : "", // 收货人姓名
        CneePeopleTel: receiving ? receiving.KaUabTel : "", // 收货人电话
        CneeProvinceCode: receiving ? receiving.KaUabProvince : "", // 收货省code
        cneeCityCode: receiving ? receiving.KaUabCity : "", // 收货市code
        CneeAreaCode: receiving ? receiving.KaUabArea : "", // 收货区code
        CneeDes: receiving ? `${receiving.KaUabDes}` : "", // 收货地详细地址
        receivInfo: deliver, // 发货地址集合
        sendInfo: receiving ? receiving : "", // 收货地址集合
        KaShprAddressbookId: deliver ? deliver.KaUserAddressbookId : "", // 发货人地址簿ID
        KaCneeAddressbookId: receiving ? receiving.KaUserAddressbookId : "", // 提货人地址薄ID
        KaGoodsTypeList: JSON.parse(sessionStorage.getItem("orderInfo")), // 货物清单
        KaGoodsTypeListStr: sessionStorage.getItem("orderInfo"), // 货物清单json串
        KaQuantity: this.number, // 件数
        KaVolume: this.M3, // 体积
        KaWeightKg: this.KG, // 重量
        KaSource: 7, // 订单来源
        KaUserId: this.kauserid, // ka用户id
        KaGoodValues: this.delivery, // 保价金额
        carrierFlag: this.res.carriageStatus, // 确认承运的标识
        EstimatedPrescription: "", // 预估时效
        IsPickUpOperate: 0,
        KaAppointmentEnd: deliver.KaAppointmentEnd, // 预约提货时间止
        KaAppointmentStart: deliver.KaAppointmentStart, // 预约提货时间起
        KaPayment: payment, // 0现付 1现付月结 2现付半月结 3现付周月结
        KaRemarks: this.maks, // 备注
        // KaTotalFreight: '', // 使用优惠券前的总费用
        // KaTotalPrice: '', // 总费用
        agencyId: this.kauserid, // 承运商id
        // companyId: kauserinfo.kaUserId, //公司id
        dayText: "今天",
        // employeeId: kauserinfo.employeeId, // 员工id
        isLoading: JSON.parse(sessionStorage.getItem("deliver_checkArr"))
          ? JSON.parse(sessionStorage.getItem("deliver_checkArr")).filter(
              (item) => item == "需要装车"
            ).length
          : "", // 是否装车
        isUnLoading: JSON.parse(sessionStorage.getItem("receiving_checkArr"))
          ? JSON.parse(sessionStorage.getItem("receiving_checkArr")).filter(
              (item) => item == "需要卸车"
            ).length
          : "", // 是否卸货车
        KaDelivery: JSON.parse(sessionStorage.getItem("receiving_checkArr"))
          ? JSON.parse(sessionStorage.getItem("receiving_checkArr")).filter(
              (item) => item == "需要送货"
            ).length
          : "", // 是否送货
        KaPickup:
          JSON.parse(sessionStorage.getItem("deliver_checkArr")) &&
          JSON.parse(sessionStorage.getItem("deliver_checkArr")).filter(
            (item) => item == "需要提货"
          )
            ? 1
            : 0, // 是否提货
        overPump: JSON.parse(sessionStorage.getItem("receiving_checkArr"))
          ? JSON.parse(sessionStorage.getItem("receiving_checkArr")).filter(
              (item) => item == "是否过磅"
            ).length
          : "", // 是否过磅
        jpLineExist: "",
        kaInputUserId: JSON.parse(localStorage.getItem("userInfo")).userId, // 录入人id
        kaInputUserName: JSON.parse(localStorage.getItem("userInfo")).userName, // 录入人名称
        proposalDiscount: null,
        // pushPlatform: '', // 推送至平台
        // PushPlatformPc: '' // 精拼报价/人工报价
      };
      Object.assign(list, JSON.parse(sessionStorage.getItem("feed"))); // 合并费用详情的字段
      Object.assign(list, JSON.parse(sessionStorage.getItem("message"))); // 合并短信配置的字段
      Object.assign(list, JSON.parse(sessionStorage.getItem("check"))); // 合并查货人的字段
      console.log(list);
      confirmSaveModifyOrder(list).then((rest) => {
        orderChange(list).then((res) => {
          console.log(res);
          Toast.success("修改成功！");
          sessionStorage.clear();
          setTimeout(() => {
            this.$router.push({
              path: "/",
            });
          }, 500);
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container_order {
  padding: 54px 18px 10px 18px;
  box-sizing: border-box;
  overflow: scroll;
  // font-size: 12px;
  width: 100%;
  height: 100%;
}
.count {
  margin-top: 10px;
  background: #ffffff;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.1);
  border-radius: 5px;
}
.count_fist {
  background: #ffffff;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.1);
  border-radius: 5px;
}
.buton {
  padding: 8px 16px;
  box-sizing: border-box;
  display: flex;
  border-radius: 5px;
  justify-content: space-around;
  background: #fff;
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  .butonO {
    background: #fff;
    width: 328px;
    height: 44px;
    border: 1px solid #f18d00;
    border-radius: 5px;
    color: #f18d00;
  }
  .butonT {
    background: #f18d00;
    width: 328px;
    height: 44px;
    margin-left: 10px;
    border-radius: 5px;
    border: 1px solid #f18d00;
  }
}
.box_added {
  box-sizing: border-box;
  background: #fff;
  margin-top: 10px;
  .checkSteper {
    padding: 10px 10px;
    box-sizing: border-box;
    font-size: 15px;
    background: #fff;
    box-sizing: border-box;
    ul {
      display: flex;
      li {
        border: 1px solid #f3f3f3;
        color: #666666;
        width: 100px;
        height: 30px;
        text-align: center;
        line-height: 30px;
        margin-right: 18px;
        background: #f3f3f3;
        border-radius: 4px;
      }
      .active {
        border: 0.5px solid #f18d00;
        color: #f18d00;
        background: #fffaf2;
      }
    }
  }
}
.cod {
  .cod_box {
    font-size: 15px;
    display: flex;
    justify-content: space-between;
    padding: 15px;
    box-sizing: border-box;
    border-bottom: 1px solid #ebedf0;
  }
}
</style>